package com.cn.pool;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;

public class NioServerBoss extends AbstractNioSelector implements Boss{

	public NioServerBoss(Executor executor,String threadName, NioSelectorRunnablePool selectorRunnablePool) {
		super(executor, threadName, selectorRunnablePool);
	}

	
	@Override
	protected void process(Selector selector) throws IOException {
		// TODO Auto-generated method stub
		
		Set<SelectionKey> selectionKeys = selector.selectedKeys();
		if (selectionKeys.isEmpty()) {
			return;
		}
		for (Iterator<SelectionKey> i = selectionKeys.iterator(); i.hasNext();) {
			SelectionKey key = i.next();
			i.remove();
			
			ServerSocketChannel server = (ServerSocketChannel) key.channel();
			//新客户端
			SocketChannel channel = server.accept();
			//设置为非阻塞
			channel.configureBlocking(false);
			//获取一个Worker
			Worker nextWorker  = getSelectorRunnablePool().nextWorker();
			//注册新客户端接入任务
			nextWorker.registerNewChannelTask(channel);
			
			System.out.println("新的客户端接入"+Thread.currentThread().getName());
			
		}
		
	}

	//注册一个任务并激活selector
	@Override
	public void registAcceptChannelTask(final ServerSocketChannel serverChannel) {
		// TODO Auto-generated method stub
		final Selector selector = this.selector;
		
		registerTask(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//注册serverChannel到selector
					serverChannel.register(selector, SelectionKey.OP_ACCEPT);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	protected int select(Selector selector) throws IOException {
		// TODO Auto-generated method stub
		return selector.select();
	
	}

}
